<?php
namespace app\service;

use plugin\saiadmin\app\logic\system\SystemConfigLogic;
use plugin\saiadmin\exception\ApiException;
use plugin\saiadmin\utils\Arr;
use GuzzleHttp\Client;

/**
 * 微信小程序服务类
 */
class WechatService
{
    /**
     * 读取配置
     * @return array|mixed|null
     */
    public static function getConfig()
    {
        $logic = new SystemConfigLogic();
        $config = $logic->getGroup('wechat_config');
        if (!$config) {
            throw new ApiException('未设置微信小程序配置');
        }
        return $config;
    }

    /**
     * 获取用户信息
     * @param string $openid
     * @param string $sessionKey
     * @param string $signature
     * @param string $iv
     * @param string $encryptedData
     * @return array
     * @throws ApiException
     */
    public static function getUserInfo(string $openid, string $sessionKey, string $signature, string $iv, string $encryptedData)
    {
        $config = static::getConfig();
        $appId = Arr::getConfigValue($config, 'appid');
        $appSecret = Arr::getConfigValue($config, 'appkey');

        // 验证签名
        $signature2 = sha1($sessionKey . $iv . $encryptedData);
        if ($signature !== $signature2) {
            throw new ApiException('签名验证失败');
        }

        // 解密用户信息
        $client = new Client();
        $url = sprintf(
            'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s',
            $sessionKey
        );

        try {
            $response = $client->post($url, [
                'json' => [
                    'code' => $encryptedData,
                    'iv' => $iv,
                    'appid' => $appId,
                    'appsecret' => $appSecret
                ]
            ]);

            $result = json_decode($response->getBody()->getContents(), true);

            if (isset($result['errcode']) && $result['errcode'] != 0) {
                throw new ApiException($result['errmsg'] ?? '获取用户信息失败');
            }

            return [
                'phoneNumber' => $result['phoneNumber'] ?? '',
                'purePhoneNumber' => $result['purePhoneNumber'] ?? '',
                'countryCode' => $result['countryCode'] ?? '',
                'watermark' => $result['watermark'] ?? ''
            ];
        } catch (\Exception $e) {
            throw new ApiException('获取用户信息失败：' . $e->getMessage());
        }
    }

    /**
     * 小程序登录
     * @param string $code
     * @param array $userInfo 用户信息
     * @return array
     * @throws ApiException
     */
    public static function login(string $code, array $userInfo = [])
    {
        if (empty($code)) {
            throw new ApiException('code不能为空');
        }

        $config = static::getConfig();
        $appId = Arr::getConfigValue($config, 'appid');
        $appSecret = Arr::getConfigValue($config, 'appkey');

        // 请求微信接口获取openid和session_key
        $client = new Client();
        $url = sprintf(
            'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code',
            $appId,
            $appSecret,
            $code
        );

        try {
            $response = $client->get($url);
            $result = json_decode($response->getBody()->getContents(), true);

            if (isset($result['errcode']) && $result['errcode'] != 0) {
                throw new ApiException($result['errmsg'] ?? '微信登录失败');
            }

            $userData = [
                'openid' => $result['openid'],
                'session_key' => $result['session_key'],
                'unionid' => $result['unionid'] ?? '',
            ];
            return $userData;
        } catch (\Exception $e) {
            throw new ApiException('微信登录失败：' . $e->getMessage());
        }
    }
}
